# -*- coding: UTF-8 -*-

# Copyright (c) 2007 Daniele Favara <nomed@dsslive.org>.
#
# This is free software you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# This software is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING.  If not, write to the Free
# Software Foundation, Inc., 51 Franilin St, Fifth Floor, Boston, MA

import sys
import database
#import select
tables = database.tables
get_tableobj = database.get_tableobj

#import update
#from tables import session

from turbogears.database import metadata, session

from sqlalchemy.sql import and_

def _insert_table(connection, table_name, **values):

    table = getattr(tables, table_name)
    u = table.insert(values=values)
    connection.execute(u)
    return True

def insert_table(loader, table_name, **kw):
    loader.log_function(__name__+'.insert_table', 'INIT', table_name, kw=kw)

    #session = loader.session
    if table_name == 'biller':
        return insert_biller(loader, **kw)
    elif table_name == 'customer':
        return insert_customer(loader, **kw)
    elif table_name == 'user':
        return insert_user(loader, **kw)

def insert_user(loader, update=False,**kw):
    loader.log_function(__name__+'.insert_user', 'INIT',  kw=kw)
    #session = loader.session
    session.begin()
    try:
        user_obj = session.query(tables.User).filter(tables.user.c.user_name==unicode(kw['user_name'])).one()

        if not update:
            print _(u"\nUser %s already exists\n"%kw['user_name'])
            sys.exit(1)

    except:
        user_obj = tables.User()
        session.save(user_obj)
    for key in loader.standard.USER_FORM:
        setattr(user_obj, key, unicode(kw[key]))
        kw.pop(key)

    session.commit()
    loader.logger.debug('Inserted: %s'%(user_obj))
    loader.log_function(__name__+'.insert_biller', 'RET', user_obj)
    return user_obj

def insert_biller(loader, **kw):
    loader.log_function(__name__+'.insert_biller', 'INIT',  kw=kw)
    #session = loader.session
    session.begin()
    try:
        user_obj = session.query(tables.User).filter(tables.user.c.user_name==kw['user_name']).one()
    except:
        user_obj = tables.User()
        session.save(user_obj)
    for key in loader.standard.USER_FORM:
        setattr(user_obj, key, kw[key])
        kw.pop(key)
    try:
        biller_obj = session.query(tables.Biller).filter(tables.biller.c.vat_code==kw['vat_code']).one()
    except:
        biller_obj = tables.Biller()
        session.save(biller_obj)
    for key, value in kw.iteritems():
        setattr(biller_obj, key, value)
    user_obj.biller.append(biller_obj)

    session.commit()
    loader.logger.debug('Inserted: %s'%(biller_obj))
    loader.log_function(__name__+'.insert_biller', 'RET', biller_obj)
    return biller_obj

def insert_customer(loader, **kw):
    loader.log_function(__name__+'.insert_customers', 'INIT',  kw=kw)
    #session = loader.session
    session.begin()

    try:
        user_obj = session.query(tables.User).filter(tables.user.c.user_name==kw['user_name']).one()
    except:
        return None
    try:
        customer_obj = session.query(tables.Customer).filter(and_(
                                        tables.customer.c.vat_code==kw['vat_code'],
                                        tables.customer.c.user_id==user_obj.user_id,
                                        tables.customer.c.fiscal_code==kw['fiscal_code'])).one()
    except:
        customer_obj = tables.Customer()
        session.save(customer_obj)
    for key, value in kw.iteritems():
        setattr(customer_obj, key, value)
    user_obj.customer.append(customer_obj)

    session.commit()
    loader.logger.debug('Inserted: %s'%(customer_obj))
    loader.log_function(__name__+'.insert_biller', 'RET', customer_obj)
    return customer_obj